package com.wmx.controller;

import com.wmx.service.AsyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;

/**********************************
 * @author wmx
 * @date 2019/9/6 14:23
 * @description:
 * @version 1.0
 ************************************/
@Slf4j
@RestController
@RequestMapping("/thread")
public class AsyncController {
    @Autowired
   private AsyncService asyncService ;

   @RequestMapping("/async")
   private Map<String,String> queryById() {
       long start = System.currentTimeMillis();
       CountDownLatch countDownLatch = new CountDownLatch(3);
       Future<String> doTaskOne = asyncService.doTaskOne(countDownLatch);
       Future<String> doTaskTwo = asyncService.doTaskTwo(countDownLatch);
       Future<String> doTaskThree = asyncService.doTaskThree(countDownLatch);



   /*    while (doTaskOne.isDone()&&doTaskTwo.isDone()&&doTaskThree.isDone()){ //所有线程执行完成后才结束循环
           break;
       }
*/
       try {
            countDownLatch.await();
           log.info("=================所有线程执行完成===========");
           System.out.println(doTaskOne.get());
           System.out.println(doTaskTwo.get());
           System.out.println(doTaskThree.get());

           long end = System.currentTimeMillis();

           log.info("所有线程执行完成后，消耗时间为："+(end-start)+"毫秒");

           HashMap<String, String> objectObjectHashMap = new HashMap<>();

           objectObjectHashMap.put("1",doTaskOne.get());
           objectObjectHashMap.put("2",doTaskOne.get());
           objectObjectHashMap.put("3",doTaskOne.get());

           return objectObjectHashMap;

       } catch (Exception e) {
           e.printStackTrace();
       }
       return  null;
   } ;
}
